﻿using System;
using System.Threading;
using System.Windows.Forms;

using DreamCube.WinForm.Common;
using DreamCube.Foundation.Basic.Utility;

namespace BGN.PlugIn.Client.Tool
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 点击部署按钮单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                DreamCube.WinForm.Common.MyProcess.CheckProcessResult result = DoCheckBGNClientRun();
                while (result == DreamCube.WinForm.Common.MyProcess.CheckProcessResult.Running)
                {
                    result = DoCheckBGNClientRun();
                }
                if (result == DreamCube.WinForm.Common.MyProcess.CheckProcessResult.Cancle) return;
                ThreadPool.QueueUserWorkItem(new WaitCallback((o) =>
                {
                    DoSetup();
                }));
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
            }
        }

        /// <summary>
        /// 执行安装客户端的方法(此方法里面一定要捕获异常，否则会导致线程的异常）
        /// </summary>
        private void DoSetup()
        {
            try
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback((o) => {
                    if (Helper.SetupActiveX())
                    {
                        MyWaitingForm.Show(this, "正在安装布谷鸟插件", false);
                        Helper.DeleteClientOldFile();
                        if (Helper.CopyFile())
                        {
                            if (Helper.HasSetupActiveX())
                            {
                                MessageBox.Show(MyWaitingForm.WaitingForm, "安装成功，确定退出安装程序！", "提醒");
                                MyWaitingForm.Hide();
                                //退出应用程序即可
                                Application.Exit();
                            }
                            else
                            {
                                //确保MessageBox显示在最前面
                                MessageBox.Show(MyWaitingForm.WaitingForm, "ActiveX插件安装失败，可能用户您取消了操作", "提醒");
                            }
                        }
                    }
                    MyWaitingForm.Hide();
                }));
                MyWaitingForm.Show(this, "正在安装ActiveX", false);
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
                MyWaitingForm.Hide();
            }
        }

        /// <summary>
        /// 窗体加载完毕之后，马上检查ActiveX的安装情况
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            
        }

        /// <summary>
        /// 检查安装环境
        /// </summary>
        private void CheckEnviroment()
        {
            try
            {
                if (MyControl.CanControlInvoke(this))
                {
                    System.Threading.Thread.Sleep(3000);
                    //这里是检查ActiveX的安装情况的
                    Boolean hasSetupActiveX = Helper.HasSetupActiveX();
                    //检查布谷鸟客户端的安装情况
                    Boolean hasSetupBGNClient = Helper.HasSetupBGNClient();
                    MyControl.ControlInvoke(this, new Action<Object>((ooo) =>
                    {
                        if (!hasSetupBGNClient)
                            lb_hasSetupBGN.Text = "您还没有安装布谷鸟客户端，请先安装布谷鸟客户端！";
                        else
                            lb_hasSetupBGN.Text = "已安装，正常！";
                        if (hasSetupActiveX)
                        {
                            lb_hasSetupActiveX.Text = "已安装；";
                            panel1.Visible = true;
                        }
                        else
                        {
                            lb_hasSetupActiveX.Text = "未安装，正常！";
                            panel1.Visible = false;
                        }
                        //设置按钮的可编辑性
                        button1.Enabled = !hasSetupActiveX && hasSetupBGNClient;
                    }), "");
                }
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
            }
        }

        /// <summary>
        /// 窗体显示之后，马上检查ActiveX的安装情况
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Shown(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback((oo) =>
            {
                CheckEnviroment();
                //执行完毕之后，关闭等待的模式窗体，让程序继续执行
                MyWaitingForm.Hide(this);
            }));
            MyWaitingForm.Show(this, "正在检查客户端环境", "检查环境", false);
        }

        /// <summary>
        /// 检查布谷鸟客户端是否正在运行中
        /// 0:还存在IE；1：不存在IE了，-1：客户取消了操作了
        /// </summary>
        /// <returns></returns>
        private DreamCube.WinForm.Common.MyProcess.CheckProcessResult DoCheckBGNClientRun()
        {
            String bgnProcessName = "SisenMESS";
            String msg = @"安装前必须先关闭布谷鸟客户端，是否马上关闭布谷鸟客户端？" + Environment.NewLine + "是：程序会马上结束布谷鸟进程" + Environment.NewLine + "否：用户您保存好自己的数据后自己退出布谷鸟客户端程序。";
            return DreamCube.WinForm.Common.MyProcess.IsProcessExits(bgnProcessName, "布谷鸟", msg);
        }

        /// <summary>
        /// 检查IE是否正在运行中
        /// 0:还存在IE；1：不存在IE了，-1：客户取消了操作了
        /// </summary>
        /// <returns></returns>
        private DreamCube.WinForm.Common.MyProcess.CheckProcessResult DoCheckIERun()
        {
            String ieProcessName = "iexplore";
            String msg = @"卸载ActiveX插件必须先关闭浏览器，是否马上关闭浏览器？" + Environment.NewLine + "是：程序会马上结束IE进程" + Environment.NewLine + "否：用户您保存好自己的数据后手动结束IE进程。";
            return DreamCube.WinForm.Common.MyProcess.IsProcessExits(ieProcessName, "IE", msg);
        }

        /// <summary>
        /// 卸载按钮单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            DreamCube.WinForm.Common.MyProcess.CheckProcessResult result = DoCheckIERun();
            while (result == DreamCube.WinForm.Common.MyProcess.CheckProcessResult.Running)
            {
                result = DoCheckIERun();
            }
            if (result == DreamCube.WinForm.Common.MyProcess.CheckProcessResult.Cancle) return;
            ThreadPool.QueueUserWorkItem(new WaitCallback((oo) =>
            {
                try
                {
                    Helper.UninstallAtiveX();
                    ThreadPool.QueueUserWorkItem((o) =>
                    {
                        CheckEnviroment();
                        MyWaitingForm.Hide(this);
                    });
                    MyWaitingForm.Show(this, "正在检查客户端环境", "检查环境", false);
                }
                catch (Exception ex)
                {
                    MyLog.MakeLog(ex);
                }
            }));
            MyWaitingForm.Show(this, "正在卸载布谷鸟ActiveX", "卸载ActiveX", false);
        }
    }
}
